package com.xiaocheng.www.transfer;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class BaseTransfer<Entity,Dto> {
    /**
     * 转换Dto
     * @param entity
     * @return
     */
    public Dto toDto(Entity entity){
        ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass();
        Class<Dto> dtoClass = (Class<Dto>) parameterizedType.getActualTypeArguments()[1];

        try {
            Dto dto = dtoClass.newInstance();
            BeanUtils.copyProperties(entity,dto);
            return dto;
        } catch (Exception e) {
            log.debug("entity 转换 Dto 失败");
            return null;
        }
    }


    /**
     * 集合转为dto
     * @param entities
     * @return
     */
    public List<Dto> toDtos(List<Entity> entities){
        List<Dto> dto = new ArrayList<>();
        entities.forEach(entity -> {
            dto.add(toDto(entity));
        });
        return dto;
    }

    /**
     * dto转为entit
     * @param dao
     * @return
     */
    public Entity toEntity(Dto dao){
        ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass();
        Class<Entity> dtoClass = (Class<Entity>) parameterizedType.getActualTypeArguments()[0];

        try {
            Entity entity = dtoClass.newInstance();
            BeanUtils.copyProperties(dao,entity);
            return entity;
        } catch (Exception e) {
            log.debug(" Dto  转换 entity 失败");
            return null;
        }
    }

    public List<Entity> toEntytys(List<Dto> dtos){
        List<Entity> entities = new ArrayList<>();
        dtos.forEach(dto -> {
            entities.add(toEntity(dto));
        });
        return entities;
    }

}
